package com.intsig.imageprocessinit;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.intsig.fireworkact.ImageScannerCommonActivity;
import com.intsig.fireworkact.ImagesToPdf;
import com.intsig.imageprocess.ImageScannerActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import preview.PreviewActivity;
import ui.BSEViewAct;
import util.SystemUtil;


public class ChooseActivity extends AppCompatActivity {

	private static String APPKEY = "421b3dd0a33ff7f8966d30f991-vagfvtRfftRgrfg";
	private static int IMAGE_SCANNER_CODE = 1001;
	private static int CAMERA_SCANNER_CODE = 1002;
	private static String mRootPath = Environment.getExternalStorageDirectory()
			.getAbsolutePath();
	private static String outPutFilePath = mRootPath + File.separator + "intsigCsPdf";
	private static String pdfOutPutFilePath = outPutFilePath + File.separator + "morepdf.pdf";
	private TextView cui_clean_id;

	private TextView tv_draw_path;
	private ArrayList<String> pathList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.init_welcome_activity);
		// new Handler().postDelayed(r, 1000);// 1秒后关闭，并跳转到主页面

		File file=new File(outPutFilePath);
		if(!file.exists()){
			file.mkdirs();
		}

		//切图
		final TextView textView = (TextView) findViewById(R.id.cui_common_id);
		textView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			if(resultList.size()>=30){
				Toast.makeText(
						ChooseActivity.this,
						"The list of pictures has reached 30 upper limit.",
						Toast.LENGTH_SHORT).show();
				return;
			}
				clickCommonFunc();
			}
		});
		final TextView cui_cs_id = (TextView) findViewById(R.id.cui_cs_id);
		cui_cs_id.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(resultList.size()>=30){
					Toast.makeText(
							ChooseActivity.this,
							"The list of pictures has reached 30 upper limit.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				clickCsFunc();
			}
		});
		final TextView cui_camera_id = (TextView) findViewById(R.id.cui_camera_id);
		cui_camera_id.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(resultList.size()>=30){
					Toast.makeText(
							ChooseActivity.this,
							"The list of pictures has reached 30 upper limit.",
							Toast.LENGTH_SHORT).show();
					return;
				}
				clickCameraFunc();
			}
		});

		final TextView cui_pdf_id = (TextView) findViewById(R.id.cui_pdf_id);
		cui_pdf_id.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				saveCsImagesToPdf();

			}
		});

		cui_clean_id= (TextView) findViewById(R.id.cui_clean_id);
		cui_clean_id.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				cui_clean_id.setText("");

				resultList.clear();
				Toast.makeText(
						ChooseActivity.this,
						"The list of pictures is empty.",
						Toast.LENGTH_SHORT).show();
			}
		});


		tv_draw_path = findViewById(R.id.tv_draw_path);
		tv_draw_path.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				opeanViewAct();
			}
		});
		checkCameraPersimion();
	}

	private void opeanViewAct() {
		Intent intent = new Intent(ChooseActivity.this,
				BSEViewAct.class);
		startActivity(intent);

	}

	/**
	 * Function: start the general API integrated edge enhancement process, the interface is simple, functional customers can customize.
	 */
	public void clickCommonFunc() {
		Intent intent = new Intent(ChooseActivity.this,
				ImageScannerCommonActivity.class);
		intent.putExtra(ImageScannerCommonActivity.EXTRA_KEY_APP_KEY, APPKEY);

		startActivity(intent);

	}


	/**
	 * Function: start the custom camera.
	 */
	public void clickCameraFunc() {
		Intent intent = new Intent(ChooseActivity.this,
				PreviewActivity.class);
		intent.putExtra(PreviewActivity.EXTRA_KEY_APP_KEY, APPKEY);

		startActivityForResult(intent, CAMERA_SCANNER_CODE);
	}

	long starttime=0;
	long endtime=0;
	public void  saveCsImagesToPdf(){
		if(resultList.size()==0) {
			Toast.makeText(
					ChooseActivity.this,
					"Please cut the edges of the picture.",
					Toast.LENGTH_SHORT).show();
			return;
		}
		if(endtime!=0)
		endtime=System.currentTimeMillis();

		if(starttime==0||endtime-starttime>2000) {
			starttime = System.currentTimeMillis();
			endtime=System.currentTimeMillis();

			Log.d("Mobile phone model：", SystemUtil.getSystemModel() + "");
			String systemModel = SystemUtil.getSystemModel();

				new ImagesToPdf().saveImagesToPdfFunc(pdfOutPutFilePath, getApplication(), APPKEY, resultList, this);

		}else{
			Toast.makeText(
					ChooseActivity.this,
					"Please do not repeat clicks.",
					Toast.LENGTH_SHORT).show();
		}
	}


	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	public static List<String> resultList=new ArrayList<String>();
	/**
	 * Function: start CS like library, with UI interface cut edge enhancement processing flow.
	 * 打开相机选择照片
	 */
	public void clickCsFunc() {
		// TODO Auto-generated method stubƒ

		Intent intent = new Intent();

		intent.setClass(ChooseActivity.this, ImageScannerActivity.class);

		intent.putExtra(ImageScannerActivity.EXTRA_KEY_APP_KEY, APPKEY);

		intent.putExtra(ImageScannerActivity.EXTRA_IMPORT_IMG_TYPE,
				ImageScannerActivity.IMPORT_FROM_GALLERY);

		intent.putExtra(ImageScannerActivity.EXTRA_KEY_JUDGE_GRAYORCOLOR,
				true);

		intent.putExtra(ImageScannerActivity.EXTRA_TRIM_IMAGE_MAXSIDE, 1599);
		// intent.putExtra(ImageScannerActivity.EXTRA_KEY_ENHANCE_MODE_INDEX,
		// ImageScannerActivity.ENHANCE_LINER_FUTURE_MODE);

		String outPutFilePath2=	outPutFilePath+ File.separator + System.currentTimeMillis()+".jpg"; // 替换成输出的图片路径

		intent.putExtra(ImageScannerActivity.EXTRA_KEY_RESULT_DATA_PATH,
				outPutFilePath2);
		startActivityForResult(intent, IMAGE_SCANNER_CODE);
	}


	/**
	 * Function: start CS with path.
	 * 进行切边处理
	 */
	public void clickCsFromCameraFunc(String result,int position) {
		// TODO Auto-generated method stub

		Intent intent = new Intent();
		initIntendParams(intent);
		String outPutFilePath2=	outPutFilePath+ File.separator + System.currentTimeMillis()+".jpg"; // 替换成输出的图片路径
		intent.putExtra(ImageScannerActivity.EXTRA_KEY_INPUTFILE_DATA_PATH,
				result);
		intent.putExtra(ImageScannerActivity.EXTRA_KEY_RESULT_DATA_PATH,
				outPutFilePath2);
		intent.putExtra(ImageScannerActivity.EXTRA_POSITON,
				position);

		startActivityForResult(intent, IMAGE_SCANNER_CODE);
	}
	//多拍
	public void clickCsFromCameraFuncList(ArrayList<String> resultList) {
		Intent intent = new Intent();
		initIntendParams(intent);
		String pathFile = outPutFilePath+ File.separator + System.currentTimeMillis(); // 替换成输出的图片路径
		intent.putStringArrayListExtra(ImageScannerActivity.EXTRA_KEY_INPUTFILE_DATA_PATH,
				resultList);
		intent.putExtra(ImageScannerActivity.EXTRA_KEY_RESULT_DATA_PATH_FILE,
				pathFile);
		startActivityForResult(intent, IMAGE_SCANNER_CODE);
	}

	public void initIntendParams(Intent intent){

		intent.setClass(ChooseActivity.this, ImageScannerActivity.class);

		intent.putExtra(ImageScannerActivity.EXTRA_KEY_APP_KEY, APPKEY);

		intent.putExtra(ImageScannerActivity.EXTRA_IMPORT_IMG_TYPE,
				ImageScannerActivity.IMPORT_FROM_FILEDIR);

		intent.putExtra(ImageScannerActivity.EXTRA_KEY_JUDGE_GRAYORCOLOR,
				false);
		intent.putExtra(ImageScannerActivity.EXTRA_TRIM_IMAGE_MAXSIDE, 1599);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK ) {

			if( requestCode == IMAGE_SCANNER_CODE) {
				final String outputPath = data
						.getStringExtra(ImageScannerActivity.EXTRA_KEY_RESULT_DATA_PATH);

				int position = data
						.getIntExtra(ImageScannerActivity.EXTRA_POSITON,0);
				position++;
				if (pathList!=null&&position<pathList.size()){
					clickCsFromCameraFunc(pathList.get(position),position);
				}else {
					pathList = null;
				}

				if (!TextUtils.isEmpty(outputPath)) {
					resultList.add(outputPath);
					cui_clean_id.setText("wipe cache【"+resultList.size()+"】");
					Toast.makeText(
							ChooseActivity.this,
							"Picture saved successfully",
							Toast.LENGTH_SHORT).show();

				}
			}else if(requestCode == CAMERA_SCANNER_CODE){

				final String result = data
						.getStringExtra(PreviewActivity.EXTRA_KEY_RESULT);
				if (result!=null&&!"".equals(result)){//单拍
					Log.e("CHOSSE_STR",result);
					clickCsFromCameraFunc(result,0);
				}else {//多拍
					pathList = data.getStringArrayListExtra(PreviewActivity.EXTRA_LIST_RESULT);
					clickCsFromCameraFunc(pathList.get(0),0);
				}
			}
		} else if (resultCode == RESULT_CANCELED
				&& requestCode == IMAGE_SCANNER_CODE) {

		}

	};



	    int MY_PERMISSIONS_REQUEST_CALL_PHONE2=2002;
	public void checkCameraPersimion(){

		List<String> grantedlist=new ArrayList<String>();

		if (ContextCompat.checkSelfPermission(ChooseActivity.this,
				Manifest.permission.CAMERA)
				!= PackageManager.PERMISSION_GRANTED) {
			grantedlist.add(Manifest.permission.CAMERA);
		//	Log.e(TAG,"add Manifest.permission.CAMERA");
		}

		if (ContextCompat.checkSelfPermission(ChooseActivity.this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE)
				!= PackageManager.PERMISSION_GRANTED) {
			grantedlist.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
		//	Log.e(TAG,"add Manifest.permission.WRITE_EXTERNAL_STORAGE");


		}
		if(grantedlist.size()!=0){
			//Log.e(TAG," size()"+grantedlist.size());

			String[] grantArray = grantedlist.toArray(new String[grantedlist.size()]);

			ActivityCompat.requestPermissions(ChooseActivity.this,
					grantArray,
					MY_PERMISSIONS_REQUEST_CALL_PHONE2);
			//权限还没有授予，需要在这里写申请权限的代码

		}else {
			//权限已经被授予，在这里直接写要执行的相应方法即可
			todosomething();
		}
	}


@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
	{   if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2)
	{
		if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
		{
			todosomething ();
		} else
		{
			// Permission Denied
			Toast.makeText(ChooseActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
		}
	}
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	}
	public void todosomething(){

    }
}
